package com.cancan.cloud.shop.filter;

import com.cancan.cloud.shop.utils.DateUtils;
import com.cancan.cloud.shop.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.cloud.gateway.route.Route;
import org.springframework.cloud.gateway.support.ServerWebExchangeUtils;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * 日志过滤器——监控埋点，请求&返回记录
 * order -2
 *
 * @author ZhouFufeng
 * @since 2020/3/12
 **/
@Component
@Slf4j
public class AuditLogGlobalFilter extends BaseGlobalFilter implements GlobalFilter, Ordered {

    @Override
    public Mono<Void> doFilter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        //获取开始时间
        String startTime = DateUtils.getCurLocalDateTimeStr();
        //获取请求路径
        String url = request.getURI().getPath();
        //获取转发的微服务名
        Route route = exchange.getAttribute(ServerWebExchangeUtils.GATEWAY_ROUTE_ATTR);
        //字符串切割 lb://服务名->服务名
        String nextServiceName = StringUtils.sub(route.getUri().toString(), 5, 0);

        log.info("url:{},nextService:{},startTime:{}", url, nextServiceName, startTime);
        //构造响应处理
        return chain.filter(exchange).then(Mono.fromRunnable(() -> {
            String endTime = DateUtils.getCurLocalDateTimeStr();
            ServerHttpResponse response = exchange.getResponse();
            HttpStatus statusCode = response.getStatusCode();
            log.info("url:{},nextService:{},startTime:{},endTime:{},httpCode:{}", url, nextServiceName, startTime, endTime, statusCode.value());
        }));
    }

    @Override
    public int getOrder() {
        //必须在 -1之前
        return -2;
    }
}